package com.dyna.service.impl;

import cn.hutool.core.util.IdUtil;
import com.dyna.service.HystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class HystrixServiceImpl implements HystrixService {
    @Override
    public String payment_Ok(Integer id) {
        return "线程池:"+Thread.currentThread().getName()+"paymentInfo_OK,id: "+id+"O(∩_∩)O";
    }

    /**
     * @fallbackMethod 要回调的方法
     * @commandProperties  设置一个值作为服务端默认访问多久返回回调结果，如果在范围内，那么执行返回结果，否则，调用异常处理方法
     */
    @Override
    @HystrixCommand(fallbackMethod = "hystrixInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")})
    public String payment_Ok_TimeOut(Integer id) {
/*//        在测试程序异常错误的时候不要抛异常
        int num = 10 / 0;*/

        try {
//            通过在这里设置不同的超时时间，返回不同的结果，一个是大于服务器默认的时间，一个是小于
            TimeUnit.SECONDS.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "线程池:"+Thread.currentThread().getName()+"paymentInfo_OK,id: "+id+"O(∩_∩)O，耗费3秒";
    }

    //    写一个异常处理方法
    public String hystrixInfo_TimeOutHandler(Integer id){
        return "线程池:"+Thread.currentThread().getName()+"系统繁忙，请稍后再试: "+id+"ㄒoㄒ，耗费3秒";
    }


    //=========服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
        if(id < 0)
        {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
    {
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }

}
